<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" label-width="120px">
      <el-form-item prop="userId" label="用户">
        <el-col :span="8">
          <el-select :disabled="dataForm.id != ''" style="width: 240px" v-model="dataForm.userId" filterable remote reserve-keyword placeholder="输入手机号或姓名" :remote-method="getUserList" :loading="loading" @change="changeUser">
            <el-option v-for="item in userList" :key="item.value" :label="item.username + '-' + item.mobile" :value="item.id"></el-option>
          </el-select>
        </el-col>
        <el-col :span="10">
          <el-form-item prop="teamId" label="课题组">
            <el-select :disabled="dataForm.id != ''" v-model="dataForm.teamId" placeholder="选择课题组" @change="changeTeam" clearable>
              <el-option v-for="team in teamList" :key="team.teamId" :label="team.teamName" :value="team.teamId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item prop="machineId" label="机器">
        <el-col :span="8">
          <el-select :disabled="dataForm.id != ''" v-model="dataForm.machineId" placeholder="选择机器" @change="changeMachine">
            <el-option v-for="machine in machineList" :key="machine.id" :label="machine.name" :value="machine.id"></el-option>
          </el-select>
        </el-col>
        <el-col :span="10">
          <el-form-item prop="projectId" label="选择项目">
            <el-select :disabled="dataForm.id != ''" v-model="dataForm.projectId" placeholder="选择项目" aria-required="true" @change="changeProject">
              <el-option v-for="project in machineProjectList" :key="project.projectId" :label="project.projectName" :value="project.projectId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="附项" v-if="dataForm.appendixOneName" style="color: #17b3a3">
        <el-col :span="6"> 名称：{{ dataForm.appendixOneName }}</el-col>
        <el-col :span="4"> 单价：{{ dataForm.appendixOnePrice }}</el-col>
        <el-col :span="10"
          >数量：
          <el-input-number :disabled="dataForm.id != ''" v-model="dataForm.appendixOneNum" @change="changeAppendixOneNum" :min="0" controls-position="right" label="请输入附项单价"></el-input-number>
        </el-col>
      </el-form-item>
      <el-form-item v-if="dataForm.machineType == 1" label="预约时间" prop="bookAllTimes">
        <el-col v-if="!dataForm.id" :span="4">
          <el-button @click="addAppointHandle(dataForm.machineId)">
            <el-icon>
              <Clock />
            </el-icon>
            选择
          </el-button>
          <order-time ref="orderTimeRef" @custom-event="handleCustomEvent"></order-time>
        </el-col>
        <el-col :span="dataForm.id ? 10 : 6" style="line-height: 24px">
          <el-text v-for="time in bookAllTimesShow" class="mx-1" type="primary">
            <el-icon>
              <Clock />
            </el-icon>
            {{ time }} <br />
          </el-text>
        </el-col>
        <el-col :span="2" style="">工时</el-col>
        <el-col :span="8">
          <el-text class="mx-1" type="primary">
            {{ dataForm.bookTotalTime }}
          </el-text>
        </el-col>
      </el-form-item>
      <el-form-item v-else label="数量" prop="bookTotalTime">
        <el-input-number :disabled="dataForm.id != ''" v-model="dataForm.bookTotalTime" @change="changeNum" controls-position="right" :min="1" label="数量"></el-input-number>
      </el-form-item>
      <el-form-item prop="actualAmount" label="实际金额">
        <el-col :span="4">
          <el-input :disabled="dataForm.id != ''" v-model="dataForm.actualAmount" placeholder="实际金额"></el-input>
        </el-col>
        <el-col :span="7">
          <el-form-item prop="couponsDiscount" label="优惠券金额">
            <el-input v-if="dataForm.id != ''" :disabled="dataForm.id != ''" v-model="dataForm.couponsDiscount" placeholder="0"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item prop="amount" label="预计金额">
            <el-input :disabled="dataForm.id != ''" v-model="dataForm.amount" placeholder="预计金额"></el-input>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="联系人" prop="contacts">
        <el-col :span="4">
          <el-input :disabled="dataForm.id != ''" v-model="dataForm.contacts" placeholder="联系人"></el-input>
        </el-col>
        <el-col :span="7">
          <el-form-item label="电话" prop="phone">
            <el-input :disabled="dataForm.id != ''" v-model="dataForm.phone" placeholder="联系人电话"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="邮箱" prop="phone">
            <el-input :disabled="dataForm.id != ''" v-model="dataForm.email" placeholder="联系人邮箱"></el-input>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="取样方式" prop="shootingWay">
        <el-radio-group :disabled="dataForm.id != ''" v-model="dataForm.shootingWay">
          <el-radio :label="0">现场</el-radio>
          <el-radio :label="1">云视频</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="取样方式" prop="way">
        <el-radio-group :disabled="dataForm.id != ''" v-model="dataForm.way">
          <el-radio :label="0">取样</el-radio>
          <el-radio :label="1">邮寄</el-radio>
          <el-radio :label="2">自带样品</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="dataForm.way == 0" label="取样地址" prop="wayDetail">
        <el-input :disabled="dataForm.id != ''" v-model="dataForm.wayDetail" placeholder="取样地址"></el-input>
      </el-form-item>
      <el-form-item label="样品备注" prop="note">
        <el-input :disabled="dataForm.id != ''" v-model="dataForm.note" type="textarea" rows="2" placeholder="样品备注"></el-input>
      </el-form-item>
      <el-form-item label="回收" prop="recycle">
        <el-radio-group :disabled="dataForm.id != ''" v-model="dataForm.recycle">
          <el-radio :label="0">是</el-radio>
          <el-radio :label="1">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="回收详情" prop="recycleDetail">
        <el-input :disabled="dataForm.id != ''" v-model="dataForm.recycleDetail" placeholder="地址及电话"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group :disabled="dataForm.teamReview == 2 || dataForm.status >= 4" v-model="dataForm.status">
          <el-radio :label="0">待取样</el-radio>
          <el-radio :label="1">进行中</el-radio>
          <el-radio :label="2">待确认</el-radio>
          <el-radio :label="3">待支付</el-radio>
          <el-radio :label="4" :disabled="true">已完结</el-radio>
          <el-radio :label="9" :disabled="true">已取消</el-radio>
          <el-radio :label="10" :disabled="true">已拒绝</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="完结方式" prop="finishType">
        <el-radio-group :disabled="true" v-model="dataForm.finishType">
          <el-radio :label="0">线上</el-radio>
          <el-radio :label="1">线下</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="dataForm.teamId != null && dataForm.teamId != '' && dataForm.teamId != '0'" :disabled="dataForm.teamReview == 2" label="团队审核" prop="teamReview">
        <el-radio-group v-model="dataForm.teamReview">
          <el-radio :label="0">审核中</el-radio>
          <el-radio :label="1">通过</el-radio>
          <el-radio :label="2">不通过</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button v-if="btnData.teamReview != 2 || dataForm.status > 3" type="primary" @click="dataFormSubmitHandle()"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { ElMessage, ElText } from "element-plus";
import OrderTime from "@/views/yckj/order-time.vue";

const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const userList = ref<any[]>([]);
const teamList = ref<any[]>([]);
const machineList = ref<any[]>([]);
const machineProjectList = ref<any[]>([]);
const bookAllTimesShow = ref<any[]>([]);
// const projectList = ref<any[]>([]);
// const projectMachineList = ref<any[]>([]);
const loading = ref(false);

const dataForm = reactive({
  id: "",
  userId: "",
  userName: "",
  teamId: "",
  projectId: null,
  projectName: "",
  machineId: null,
  machineName: "",
  machineType: 1,
  contacts: "",
  phone: "",
  email: "",
  // bookTime: "",
  // bookStartTime: "",
  // bookEndTime: "",
  bookAllTimes: "",
  bookTotalTime: 0,
  finishType: 0,
  way: 0,
  wayDetail: "",
  shootingWay: 0,
  note: "",
  recycle: 0,
  recycleDetail: "",
  amount: 0,
  actualAmount: "",
  couponsDiscount: "",
  status: 0,
  teamReview: 0,

  price: 0, //单价

  appendixOneName: "",
  appendixOnePrice: 0,
  appendixOneNum: 0
});

const btnData = reactive({
  teamReview: 0
});

const rules = ref({
  userId: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  userName: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  projectId: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  projectName: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  machineId: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  machineName: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  // actualAmount: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  contacts: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  phone: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  bookAllTimes: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  bookTotalTime: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  // bookStartTime: [{required: true, message: '必填项不能为空', trigger: 'blur'}],
  // bookEndTime: [{required: true, message: '必填项不能为空', trigger: 'blur'}],
  way: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  recycle: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  status: [{ required: true, message: "必填项不能为空", trigger: "blur" }]
});

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";
  dataForm.userId = "";
  dataForm.teamId = "";
  dataForm.bookAllTimes = "";
  dataForm.bookTotalTime = 0;

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }
  //获取项目列表
  Promise.all([getUserList(""), getMachineList()]).then(() => {
    if (id) {
      getInfo(id);
    }
  });
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/yckj/order/" + id).then((res) => {
    Object.assign(dataForm, res.data);
    btnData.teamReview = dataForm.teamReview;
    if (dataForm.machineId) {
      getMachineProjectList(dataForm.machineId);
    }
    if (dataForm.userId != "") {
      getTeamList(parseInt(dataForm.userId));
    }
    handleAllTimes();
  });
};
// 获取用户列表
const getUserList = async (query: string) => {
  loading.value = true;
  const res = await baseService.get("/yckj/user/list", { key: query });
  userList.value = res.data;
  loading.value = false;
};

// 获取组列表
const getTeamList = async (value: number) => {
  const res = await baseService.get("/yckj/teamrelation/list", { userId: value });
  teamList.value = res.data;
};

// 获取项目列表
const getMachineList = async () => {
  const res = await baseService.get("/yckj/machine/list");
  machineList.value = res.data;
};

// 获取项目列表-根据机器Idd
const getMachineProjectList = async (value: number) => {
  const res = await baseService.get("/yckj/projectmachine/list", { machineId: value });
  machineProjectList.value = res.data;
};

// // 获取项目列表
// const getProjectList = async () => {
//   const res = await baseService.get("/yckj/project/list");
//   projectList.value = res.data;
// };

// // 获取机器列表-根据项目Id
// const getProjectMachineList = async (value: number) => {
//   const res = await baseService.get("/yckj/projectmachine/list", {projectId: value});
//   projectMachineList.value = res.data;
// };

const changeUser = (value: number) => {
  const selectedItem = userList.value.find((item) => item.id === value);
  dataForm.userName = selectedItem.username;
  dataForm.contacts = dataForm.userName;
  dataForm.phone = selectedItem.mobile;
  dataForm.teamId = "";
  getTeamList(value);
};

const changeTeam = (value: number) => {
  // console.log(value);
};

const changeMachine = (value: number) => {
  const selectedItem = machineList.value.find((item) => item.id === value);
  dataForm.machineName = selectedItem.name;
  dataForm.machineType = selectedItem.type;
  dataForm.projectId = null;
  getMachineProjectList(value);
  dataForm.amount = 0;
  // dataForm.amount = selectedItem.price;
  // dataForm.price = selectedItem.price;
};

const changeProject = (value: number) => {
  const selectedItem = machineProjectList.value.find((item) => item.projectId === value);
  dataForm.projectName = selectedItem.projectName;
  dataForm.amount = selectedItem.price;
  dataForm.price = selectedItem.price;
  dataForm.appendixOneName = selectedItem.appendixOneName;
  dataForm.appendixOnePrice = selectedItem.appendixOnePrice;
  dataForm.appendixOneNum = 0;
  if (dataForm.machineType === 0) {
    dataForm.bookTotalTime = 0;
  } else {
    dataForm.amount = dataForm.price * dataForm.bookTotalTime + dataForm.appendixOnePrice * dataForm.appendixOneNum;
  }
};

//修改预约时间数量
const changeNum = (value: number) => {
  dataForm.amount = dataForm.price * value + dataForm.appendixOnePrice * dataForm.appendixOneNum;
};

//修改附项数量
const changeAppendixOneNum = (value: number) => {
  dataForm.appendixOneNum = value;
  dataForm.amount = dataForm.price * dataForm.bookTotalTime + dataForm.appendixOnePrice * value;
};

// const changeProject = (value: number) => {
//   const selectedItem = projectList.value.find((item) => item.id === value);
//   dataForm.projectName = selectedItem.name;
//   dataForm.machineId = null;
//   getProjectMachineList(value);
// };

// const changeMachine = (value: number) => {
//   const selectedItem = projectMachineList.value.find((item) => item.machineId === value);
//   dataForm.machineName = selectedItem.machineName;
//   dataForm.amount = selectedItem.price;
//   dataForm.price = selectedItem.price;
// };

const handleCustomEvent = (value: any) => {
  dataForm.bookAllTimes = value.toString();
  let num = value.length / 2;
  dataForm.bookTotalTime = num;
  dataForm.amount = dataForm.price * num + dataForm.appendixOnePrice * dataForm.appendixOneNum;
  handleAllTimes();
};

const handleAllTimes = () => {
  let allTimes: string[] = [];
  let times = dataForm.bookAllTimes.split(",");
  for (let i = 0; i < times.length; i++) {
    let time = times[i];
    const date = new Date(time);
    date.setMinutes(date.getMinutes() + 30);
    let hours = date.getHours().toString().padStart(2, "0"); // 获取小时并补零
    if (hours == "00") {
      hours = "24";
    }
    const minutes = date.getMinutes().toString().padStart(2, "0"); // 获取分钟并补零
    const show = time + "~" + hours + ":" + minutes;
    allTimes.push(show);
  }
  bookAllTimesShow.value = allTimes;
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)("/yckj/order", dataForm).then((res) => {
      ElMessage.success({
        message: "成功",
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

const orderTimeRef = ref();
const addAppointHandle = (machineId: any) => {
  orderTimeRef.value.addAppoint(machineId);
};
defineExpose({
  init
});
</script>
